'''
 * CaRComp Execution Environment
 * 
 * Copyright (C) 2011 Taylor L. Riche
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
'''

import queue

class Endpoint(object):
    '''
    A wrapper class for the combination of a Implementation and a Port that 
    represents one end of a Connector.
    '''
    
    def __init__(self, comp, port):
        '''
        Constructor
        
        Takes a Implementation and a Port within that Implementation.
        '''
        self._comp = comp
        self._port = port
        
    def get_comp_name(self):
        '''
        Returns name of the Implementation.
        '''
        return self._comp.get_name()
    
    def get_port_name(self):
        '''
        Returns name of the Port.
        '''
        return self._port.get_name()
    
    def get_name(self):
        '''
        Returns a name for the Endpoint that is a combination of the Implementation and Port names.
        '''
        return self.get_comp_name() + ":" + self.get_port_name()
    
    
class Connector(object):
    '''
    A class that represents communication between two Ports. Uses instances of the Endpoint
    class to represent the source and destination of the Connector. Contains a private instance
    of the queue.Queue class to support communication between two threads.
    '''
    
    def __init__(self, src, dst):
        '''
        Constructor
        
        Takes a source Endpoint and a destination Endpoint.
        '''
        self._source = src
        self._dest = dst
        self._queue = queue.Queue(100)
        
    def instrument(self, root=None, uid=None):
        '''
        Returns an InstrumentedConnector with the same endpoints
        '''
        if uid is None:
            uid = '0'
        fn = 'i_{}-{}_o_{}-{}_u_{}.txt'.format(self.get_src_comp_name(), self.get_src_port_name(), 
                                               self.get_dest_comp_name(), self.get_dest_port_name(), uid)
        if root is not None:
            fn = root + fn
        iconn = InstrumentedConnector(self._source, self._dest, fn)
        return iconn

    def get(self):
        '''
        Return and remove a message from the internal Queue.
        
        Throws an exception of type queue.Empty after 1 seconds of waiting.
        '''
        
        return self._queue.get(True, .01)
    
    def get_dest_port_name(self):
        '''
        Returns name of the destination Port.
        '''
        return self._dest.get_port_name()
    
    def get_src_port_name(self):
        '''
        Returns the name of the source Port.
        '''
        return self._source.get_port_name()
    
    def get_src_comp_name(self):
        '''
        Returns the name of the source Endpoint.
        '''
        return self._source.get_comp_name()
    
    def get_dest_comp_name(self):
        '''
        Returns the name of the destination Endpoint.
        '''
        return self._dest.get_comp_name()
    
    def get_src_name(self):
        '''
        Returns the name of the source Endpoint.
        '''
        return self._source.get_name()
    
    def get_dest_name(self):
        '''
        Returns the name of the destination Endpoint.
        '''
        return self._dest.get_name()
    
    def get_name(self):
        '''
        Returns the name of the Connector. This is a string created by appending
        the source and destination Endpoint names.
        '''
        return self._source.get_name() + "->" + self._dest.get_name()
    
    def put(self, msg):
        '''
        Put msg on the internal Queue. Blocks if Queue is full.
        '''
        self._queue.put(msg, True)
        
    def get_src_comp(self):
        return self._source._comp
    
    def get_dst_comp(self):
        return self._dest._comp
    
    def get_src(self):
        return self._source
    
    def get_dst(self):
        return self._dest
    
class InstrumentedConnector(Connector):
    '''
    Provides the same functionality as the Connector class but also records 
    messages that pass through it.
    '''
    
    def __init__(self, src, dst, file=None):
        Connector.__init__(self, src, dst)
        self._log = []
        self._filename = None
        #print('{}++{} -> {}'.format(src.get_name(), dst.get_name(), file))
        if file is not None:
            self._filename = file
        
    def put(self, msg):
        Connector.put(self, msg)
        self._log.append(msg)
        #print('logging {}'.format(msg))
    
    def checkpoint(self, file_arg=None):
        '''
        Saves the logged messages to disk using the filename given.
        '''
        if file_arg is None:
            filename = self._filename
        else:
            filename = file_arg
        file = open(filename, 'w')
        for msg in self._log:
            file.write(msg)

